// ws.cjs
import express from 'express'
import cors from 'cors'
//到头来，还是位置放错了！！！
import dotenv from 'dotenv';
dotenv.config(); // 加载 .env 文件中的环境变量
// console.log(process.env.COZE_API_Token)

import {chatStream, chatCoze, chatOpenAI} from "./controllers/chatStream.mjs";
import {generateState} from "./utils/generateState.mjs";
import axios from "axios";
import {formatResponse} from "./utils/format.mjs";


const app = express();
const port = 3010;

const map=new Map();


//连接mysql
app.use(express.json()); // 内置中间件，用于解析JSON请求体
app.use(cors())

app.get('/chat', async (req, res)=> {
    const token=req.headers.authorization
    //校验[客户端数据]，COZE API后续也会校验此Web后端程序数据
    if(token===map.get('token')){
        await chatStream(req, res)
    }else{
        res.status(500).json({
            error: '认证失败，请重新登录认证',
        });
    }

});


app.get('/login',(req,res)=>{
    try {
        const state=generateState();
        axios.get("https://www.coze.cn/api/permission/oauth2/authorize",
            {
                params:{
                    response_type:"code",
                    client_id:"74253506040755569235933973741421.app.coze",
                    redirect_uri:"http://localhost:3000/auth/callback",
                    state:state
                },
                maxRedirects: 0, // 关键配置：禁止自动重定向
                validateStatus: (status) => status === 302 // 允许302状态
            }
        ).then(response=>{
            // 提取Location头
            const redirectUrl = response.headers.location;
            if (!redirectUrl) {
                throw new Error('Missing Location header in 302 response');
            }
            res.json({
                data:{
                    res: redirectUrl,
                    state // 需要存储用于后续校验
                },
                code:200
            });
        })
    }catch (error){
        console.error('授权初始化失败:', error.message);
        res.status(500).json({
            error: '无法启动授权流程',
            details: error.response?.data
        });
    }

})

//SSE只能用Get请求
app.get('/chatStream', async (req, res)=> {
    // console.log(token);
    // process.env.COZE_API_Token=token;
    await chatCoze(req, res)
})

//用于接收code，并通过code请求token
app.get('/auth/callback',(req,res)=>{
    const code = req.query.code;
    try {
        axios.post("https://api.coze.cn/api/permission/oauth2/token", {
            client_id: "74253506040755569235933973741421.app.coze",
            redirect_uri: "http://localhost:3000/auth/callback",
            code: code,
            grant_type: 'authorization_code'
        }, {
            headers: {
                'Content-Type': 'application/json',
                'Authorization':' Bearer XJFNtLV78DuYtMMgJBXQyN5b8TcPe5TIvNClPv7qlD5vHgC1'
            }
        }).then(response=>{
            const accessToken = response.data.access_token;
            map.set("token",accessToken)
            process.env.COZE_API_Token=accessToken;
            // 你可以将 accessToken 返回给前端，或者存储在会话中
            res.json(formatResponse(accessToken));
        });
        
    } catch (error) {
        console.error('Error fetching token:', error);
        res.status(500).send('Error fetching token');
    }
})

app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});

